const koa = require('koa');
const app = new koa();
const serv = require('koa-static');

const convert = require('koa-convert');

const path = require('path');
app.use(serv(path.resolve(__dirname, '..', 'files')));

// 全局处理工具
global.app_config = require('./app_config.conf'); // 应用服务基本环境配置
require('../tools/_include.t');
require('../tools/_Array.t');

// session
const session = require('koa-session');
app.keys = ['keys', 'keykeys'];
app.use(convert(session(app)));

// 日志文件管理
const log4js = require('koa-log4');
app_config.is_dev ? true : log4js.configure('server/log4js.json');
app.use(log4js.koaLogger(log4js.getLogger('app'), {
  level: 'auto'
}));

const cors = require('koa-cors')({ // 中间件，只允许部分域名访问此域
  origin: function(ctx) {
    /*
     * 要获取客户端的ip地址，如果用了nginx通过域名代理服务，
     * 必须在nginx服务配置中的location中添加
     * location / {
     *      proxy_set_header X-Real-IP $remote_addr;
     *      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     *      proxy_set_header Host $http_host;
     *      proxy_pass http:*127.0.0.1:yourAppPort;
     * }
     * 不使用nginx服务，客户端的ip为ctx.socket.remoteAddress
     * 使用nginx服务，ip=ctx.headers['x-forwarded-for']
     */
    _origin = ctx.header.origin || '*';
    console.log('客户端访问地址：', ctx.headers['x-forwarded-for'] || ctx.socket.remoteAddress);
    console.log('客户端origin:', _origin);
    // console.log('_origin:', _origin)
    // console.log(ctx)
    if (_origin == 'null' || _origin.indexOf('chrome-extension') > -1 || _origin.indexOf('dotnar.com') > -1 || _origin.indexOf('127.0.0.1') > -1 || _origin.indexOf('shengyi8888.com') > -1 || _origin.indexOf('localhost:') > -1 || _origin == '*') {
      return _origin;
    };
    console.log('?');
    return '*';
  },
  credentials: true,
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS'
});
app.use(convert(cors));

// 中间件，判断方法接口是否被访问域名执行
app.use(co.wrap(function*(ctx, next) {
  var _url = ctx.request.url;
  var _origin = ctx.header.origin || '*';
  if (_origin == 'null' || _origin.indexOf('chrome-extension') > -1 || _origin.indexOf('dotnar.com') > -1 || _origin.indexOf('127.0.0.1') > -1 || _origin.indexOf('shengyi8888.com') > -1 || _origin.indexOf('localhost:') > -1 || _origin == '*') {
    yield next();
  };
}));


co(function*() {
  console.time('api Init complete'.info);

  // mongodb
  const MongoClient = require('mongodb').MongoClient;
  global.ObjectID = require('mongodb').ObjectID;
  global.mongo = require('../tools/mongo.t');
  global.db = yield MongoClient.connect('mongodb://127.0.0.1:27017/files-system');


  const router = yield require('../complex/complex');
  router.apis.push({
    name: 'getAllApis',
    content: '获取所有接口描述',
    apiroot: '/allApis'
  });
  router.router.get('/allApis', function*() {
    this.body = router.apis;
  });

  app.use(convert(router.router.routes()));
  app.use(convert(router.router.allowedMethods()));
  console.timeEnd('api Init complete'.info);

  app.listen(2009);
  console.log(('server start at 2009,' + new Date().toLocaleString()).data);
}).catch(e => {
  console.log('start err:', e);
  console.log(new Date().toLocaleString());
});
